/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import entity.EventInfo;
import entity.Registration;
import entity.UserInfo;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.ServletContext;
import model.RegistrationFacade;

/**
 *
 * @author VietTien
 */
@ManagedBean
@SessionScoped
public class RegistrationController {

    @EJB
    private RegistrationFacade registrationFacade;
    private Registration current;//Select current row
    private DataModel items = null;//Lay list event
    private List<Registration> eventList;
    UserInfo user;
    EventInfo currentEvent;
    EventController eventControl;
    private Registration reg;

    public Registration getReg() {
        return reg;
    }

    public void setReg(Registration reg) {
        this.reg = reg;
    }

    public EventInfo getCurrentEvent() {
        return currentEvent;
    }

    public void setCurrentEvent(EventInfo currentEvent) {
        this.currentEvent = currentEvent;
    }

    /** Creates a new instance of RegistrationController */
    public RegistrationController() {
        user = (UserInfo) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
        eventControl = new EventController();
    }

    public String TakeIn(EventInfo evt) {
        current = registrationFacade.checkTakeIn(user, evt);
        if (current == null) {    //not take in
            currentEvent = new EventInfo();
            currentEvent = evt;
            System.out.println("Event current" + currentEvent);
            current = new Registration();
            current.setUserInfo(user);
            current.setEventInfo(currentEvent);
            current.setStatusReg("Pending");
            current.setRegTime(new Date());
            current.setCancelTime(null);
            current.setIsDelete(false);
            registrationFacade.createReg(current, currentEvent);
            JsfUtil.addSuccessMessage("Send request participate successfull !");
            EventController e = new EventController();
            e.setItems(null);
            recreateModel();
            return "event";
        } else {
            //has cancel
            current.setCancelTime(null);
            registrationFacade.edit(current);
        }
        return "event";
    }

    public String TakeInViewPage(EventInfo evt) {
        current = registrationFacade.checkTakeIn(user, evt);
        if (current == null) {    //not take in
            currentEvent = new EventInfo();
            currentEvent = evt;
            System.out.println("Event current" + currentEvent);
            current = new Registration();
            current.setUserInfo(user);
            current.setEventInfo(currentEvent);
            current.setStatusReg("Pending");
            current.setRegTime(new Date());
            current.setCancelTime(null);
            current.setIsDelete(false);
            registrationFacade.create(current);
            JsfUtil.addSuccessMessage("Send request participate successfull !");
            recreateModel();
            return "SendRequestSuccess";
        } else {
            //has cancel
            current.setCancelTime(null);
            registrationFacade.edit(current);
        }
        return "SendRequestSuccess";
    }

    public DataModel getItems() {

        return items;
    }

    public String CancelRequest(EventInfo evt) {

        current.setCancelTime(new Date());
        registrationFacade.edit(current);
        return "event";
    }

    public boolean checkTakeIn(EventInfo evt) {

        reg = registrationFacade.checkTakeIn(user, evt);
        //reg == null --> has not taken in  --> return true --> Parti
        //reg != null && reg.CancelTime != null  --> cancel --> return true --> Parti
        //reg != null && reg.getCanTime == null --> has taken in  -->return false -->Cancel
        if (reg != null) {
            return false;

        }
        return true;
    }

    public String Cancel(EventInfo evt) {
        current = registrationFacade.checkTakeIn(user, evt);
        current.setCancelTime(new Date());
        registrationFacade.edit(current);

        return "event";
    }

    public String prepareViewParticipateEvt(EventInfo evt) {
        currentEvent = evt;
        itemsRegEvt = null;
        return "ViewParticipateEvent";
    }
    private DataModel itemsRegEvt;

    public DataModel getItemsRegEvt() {
        if (itemsRegEvt == null) {
            itemsRegEvt = new ListDataModel(registrationFacade.findRegByEvent(currentEvent));
        }
        return itemsRegEvt;
    }

    public boolean checkStartTimeEvt() {
        if (currentEvent.getStartEvent().after(new Date())) {
            return false;
        }
        return true;
    }

    public void setItemsRegEvt(DataModel itemsRegEvt) {
        this.itemsRegEvt = itemsRegEvt;
    }

    public String setStatusRegistration() {
        current = (Registration) itemsRegEvt.getRowData();
        if (current.getStatusReg().equals("Pending") || current.getStatusReg().equals("Cancel")) {
            current.setStatusReg("Accept");
        } else {
            current.setStatusReg("Cancel");
        }
        registrationFacade.edit(current);
        JsfUtil.addSuccessMessage("Status have successfull update !");
        return "ViewParticipateEvent";
    }
    private Date today = new Date();

    public Date getToday() {
        return today;
    }

    public void setToday(Date today) {
        this.today = today;
    }
    private UserInfo currentUser;

    //prepare view detail Registration of an UserInfo
    public String prepareViewParticipateUser() {
        currentUser = (UserInfo) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
        itemsRegEvt = null;
        return "/Event/MyParticipateEvent";
    }
    private DataModel itemsRegUser;

    public DataModel getItemsRegUser() {
        if (itemsRegUser == null) {
            itemsRegUser = new ListDataModel(registrationFacade.findRegByUser(currentUser));
        }
        return itemsRegUser;
    }

    public void setItemsRegUser(DataModel itemsRegUser) {
        this.itemsRegUser = itemsRegUser;
    }

    public String cancelMyRegistration() {
        current = (Registration) itemsRegUser.getRowData();
        registrationFacade.remove(current);
        JsfUtil.addSuccessMessage("Cancel participate event successful !");
        recreateModel();
        return "MyParticipateEvent";
    }

    private void recreateModel() {
        items = null;
        itemsRegEvt = null;
        itemsRegUser = null;

    }

    public String setStatusAccept() {
        current = (Registration) itemsRegEvt.getRowData();
        current.setStatusReg("Accept");
        current.setCancelTime(null);
        registrationFacade.edit(current);
        eventList = (List<Registration>) currentEvent.getRegistrationCollection();
        eventList.get(itemsRegEvt.getRowIndex()).setStatusReg("Accept");
        currentEvent.setRegistrationCollection(eventList);
        JsfUtil.addSuccessMessage("Status Event Accepted");
        return "ViewParticipateEvent";
    }

    public String setStatusCancel() {
        current = (Registration) itemsRegEvt.getRowData();
        current.setStatusReg("Cancel");
        current.setCancelTime(today);
        //update to Registration table
        registrationFacade.edit(current);

        //update to Event Registration Collection
        eventList = (List<Registration>) currentEvent.getRegistrationCollection();
        eventList.get(itemsRegEvt.getRowIndex()).setStatusReg("Cancel");
        currentEvent.setRegistrationCollection(eventList);

        JsfUtil.addSuccessMessage("Status event canceled");
        return "ViewParticipateEvent";
    }
    /*
     * check number of participate player
     * return false if number of Reg player < Max player --> Admin can Accept this Reg
     * return true --> can not Accept anymore
     */

    public boolean isMaxPlayer() {
        //number of max player of an event
        int numMaxPlayer = currentEvent.getMaxPlayer();
        //number of reg player of an event
        int numAcceptPlayer = 0;
        for (Registration reg : currentEvent.getRegistrationCollection()) {
            if (reg.getStatusReg().equals("Accept")) {
                numAcceptPlayer++;
            }
        }
        //check
        if (numAcceptPlayer >= numMaxPlayer) //max
        {
            return true;
        }
        return false;
    }
    private DataModel itemsRegAccept;

    public DataModel getItemsRegAccept() {
        if (itemsRegAccept == null) {
            itemsRegAccept = new ListDataModel(registrationFacade.findRegAccepEvent(currentEvent));
        }
        return itemsRegAccept;
    }

    public void setItemsRegAccept(DataModel itemsRegAccept) {
        this.itemsRegAccept = itemsRegAccept;
    }

    public void preProcessPDF(Object document) throws IOException,
            BadElementException, DocumentException {
        Document pdf = (Document) document;
        pdf.open();
        pdf.setPageSize(PageSize.A4);

        //get image for logo
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        String logo = servletContext.getRealPath("") + File.separator + "images"
                + File.separator + "prime_logo.png";

        //try catch if file not found
        try {
            pdf.add(Image.getInstance(logo));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        Font font = new Font(Font.TIMES_ROMAN, 30, Font.BOLD);
        //header
        Paragraph paragraph = new Paragraph("LIST ACCEPTED PARTICIPATE REGISTRATION", font);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        pdf.add(paragraph);
        pdf.add(new Paragraph("Event Name: " + currentEvent.getEventName()));
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
        //pdf.add(new Paragraph("Create By :" + stf.getFullName() ));   //name of current user
        pdf.add(new Paragraph("Create Date :" + sdf.format(new java.util.Date())));
        pdf.add(new Paragraph("Totals: " + itemsRegAccept.getRowCount()));   //totals items
        pdf.add(new Paragraph(" ", font));
    }
}
